﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Telerik.Web.Mvc;
using Telerik.Web.Mvc.Extensions;
using Telerik.Web.Mvc.UI.Fluent;
using System.Web.Mvc;
using WaterRegimenMonitor.Common;
using WaterRegimenMonitor.Web.Domain;

namespace WaterRegimenMonitor.Web.Code
{
    /// <summary>
    /// UI处理辅助类。
    /// </summary>
    /// <remarks></remarks>
    public class UIHelper
    {
        public static GridModel<T> GetGridModelFromQueryModel<T>(IQueryable<T> source, JosnPagingQueryModel query)
        {
            return GetGridModelFromQueryModel(source, query.page, query.limit,
                                              GetCommonSortDescriptorFromSortModel(query.SortModel),
                                              GetCommonFilterFromFilterModel(query.FilterModel));
        }

        public static GridModel<T> GetGridModelFromQueryModel<T>(IQueryable<T> source, int page, int pageSize, List<SortDescriptor> sortModels, IEnumerable<IFilterDescriptor> filterModels)
        {
            var data = source.ToGridModel(page, pageSize, sortModels, filterModels, new List<GroupDescriptor>()); // there is no group condition.

            return new GridModel<T>
            {
                Data = data.Data as IEnumerable<T>,
                Total = data.Total,
                Aggregates = data.Aggregates
            };
        }

        public static List<SortDescriptor> GetCommonSortDescriptorFromSortModel(IEnumerable<JosnQuerySortModel> sortModels)
        {
            //convert the sort description.
            var sortList = new List<SortDescriptor>();
            foreach (var item in sortModels)
            {
                sortList.Add(new SortDescriptor()
                {
                    Member = item.property,
                    SortDirection = item.direction.ToLower() == "desc" ? ListSortDirection.Descending : ListSortDirection.Ascending
                });
            }
            return sortList;
        }

        public static List<IFilterDescriptor> GetCommonFilterFromFilterModel(IEnumerable<JosnQueryFilterModel> filterModels)
        {
            //just for the string like filter.
            var filterList = new List<IFilterDescriptor>();

            foreach (var item in filterModels)
            {
                //判断是否指定了属性值
                if (string.IsNullOrEmpty(item.value))
                {
                    continue;
                }

                //判断是否指定了开始日期
                if (item.property.EndsWith("_L"))
                {
                    //获得属性值
                    DateTime targetDate = DateTime.Parse(item.value);

                    //获得属性名称
                    string propertyName = item.property.Substring(0, item.property.LastIndexOf('_'));

                    //添加过滤
                    filterList.Add(new FilterDescriptor(propertyName, FilterOperator.IsGreaterThanOrEqualTo, targetDate));
                }
                //判断是否指定了结束日期
                else if (item.property.EndsWith("_H"))
                {
                    //获得属性值
                    DateTime targetDate = DateTime.Parse(item.value);

                    //添加一天
                    targetDate = targetDate.AddDays(1);

                    //获得属性名称
                    string propertyName = item.property.Substring(0, item.property.LastIndexOf('_'));

                    //添加过滤
                    filterList.Add(new FilterDescriptor(propertyName, FilterOperator.IsLessThanOrEqualTo, targetDate));
                }
                //判断是否指定了组织结构
                else if (item.property == "unit_code")
                {
                    //获得当前用户
                    UserPrincipal principal = Helper.CurrentPrincipal;

                    //获得组织结构代码
                    string unitCode = principal.User.Organization.Organization_Code;

                    //去掉末尾的0
                    unitCode = unitCode.TrimEnd('0');

                    //获得属性值
                    string code = item.value;

                    //判断是否有效
                    if (code.StartsWith(unitCode))
                    {
                        unitCode = code.TrimEnd('0');
                    }

                    //添加过滤
                    filterList.Add(new FilterDescriptor(item.property, FilterOperator.StartsWith, unitCode));
                }
                else
                {
                    filterList.Add(new FilterDescriptor(item.property, FilterOperator.Contains, item.value));
                }
            }
            return filterList;
        }

        /// <summary>
        /// 获得指定视图导航动作的地址。
        /// </summary>
        /// <param name="view">要获得导航动作地址的视图。</param>
        /// <returns>
        /// 指定视图导航动作的地址。
        /// </returns>
        /// <history>
        /// [ZengE]               2012/3/24 13:17    创建
        ///   </history>
        public static string GetCurrentActionUrl(WebViewPage view)
        {
            //用于保存动作名称
            string actionName = string.Empty;

            //用于保存值
            object value = null;

            //获得动作名称
            if (view.ViewContext.RouteData.Values.TryGetValue("action", out value) && null != value)
            {
                //设置动作名称
                actionName = value.ToString();
            }

            //判断是取得了动作名称
            if (string.IsNullOrEmpty(actionName))
            {
                //如果没有取得，则默认为默认动作
                actionName = "Index";
            }

            //用于记录当前动作路径
            string actionUrl = view.Url.Action(actionName);

            //判断是否为默认动作
            if (string.Compare("Index", actionName, true) == 0)
            {
                //在地址上附加默认动作名称
                actionUrl = actionUrl + "/" + actionName;
            }

            //返回动作地址
            return actionUrl;
        }
    }
}